﻿using System; 
using System.Collections.Generic;
using UnityEngine;


namespace XFGameFramework
{
     
    public class EventManager
    {

        private static Dictionary<string, Action<object[]>> events = new Dictionary<string, Action<object[]>>();

        [RuntimeInitializeOnLoadMethod]
        static void Init() {
            events.Clear();
        }

        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="name">事件名称</param>
        /// <param name="args">参数</param>
        public static void TriggerEvent(string name, params object[] args)
        {

            Action<object[]> action = null;
            if (events.TryGetValue(name, out action))
            {
                action?.Invoke(args);
            }
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="callback">回调</param>
        public static void AddEvent(string eventName, Action<object[]> callback)
        {

            if (events.ContainsKey(eventName))
            {
                events[eventName] += callback;
            }
            else
            {
                Action<object[]> action = null;
                action += callback;
                events.Add(eventName, action);
            }

        }

        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="callback">回调</param>
        public static void RemoveEvent(string eventName, Action<object[]> callback)
        {

            Action<object[]> action = null;
            if (events.TryGetValue(eventName, out action))
            {
                action -= callback;
                if (action == null)
                    events.Remove(eventName);
            }

        }

    }

}

